package nkr1pt.popkorn.interact;

import com.google.inject.Inject;
import java.io.InputStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;

/**
 * Interacts with the user through the command line.
 *
 * @author Kristof Vanhaeren
 */
public class Interactor {

    private Scanner scanner;
    private ConsoleStatusView consoleStatusView;
    private static final Logger logger = Logger.getLogger(Interactor.class.getName());
    private String[][] interactCommands = new String[][]{
        {"help", "Shows valid commands"},
        {"status", "Shows the current status of Popkorn"},
        {"quit", "Exit Popkorn"}};

    @Inject
    public Interactor(InputStream is, ConsoleStatusView consoleStatusView) {
        scanner = new Scanner(is);
        this.consoleStatusView = consoleStatusView;
    }

    public void start() {
        Thread thread = new Thread(new Runnable() {

            public void run() {
                while (true) {
                    String input = getNextInput();
                    if (!StringUtils.isEmpty(input)) {
                        handleInput(input);
                    }
                }
            }
        }, "Interactor");
        thread.start();
    }

    public void handleInput(String input) {
        if (input.equals("help")) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String[] command : interactCommands) {
                stringBuilder.append(command[0] + " - " + command[1] + "\n");
            }
            System.out.println(stringBuilder.toString());
        } else if (input.equals("status")) {
            System.out.println(consoleStatusView.getView());
        } else if (input.equals("quit")) {
            logger.log(Level.INFO, "Popkorn will now quit");
            System.exit(0);
        } else {
            logger.log(Level.INFO, "Unknown command: " + input);
        }
    }

    public String getNextInput() {
        if (scanner.hasNext()) {
            return scanner.next();
        }

        return null;
    }

}